package org.embedchat.protocol.codec;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;

import org.embedchat.protocol.message.AbstractMessage;

public abstract class AbstractMessageEncoder implements MessageEncoder {
	
	private final int type;

	protected AbstractMessageEncoder(int type) {
		this.type = type;
	}

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		System.out.println("encode");
		AbstractMessage m = (AbstractMessage) message;
		ByteBuffer buf = ByteBuffer.allocate(16);
		buf.setAutoExpand(true);
		buf.putShort((short)type);
		buf.putLong(m.getMessageBodyLength());
		encodeBody(session, m, buf);
		buf.flip();
		out.write(buf);
	}

	protected abstract void encodeBody(IoSession session,
			AbstractMessage message, ByteBuffer out);
}
